import 'package:flutter/material.dart';

class MonthSlider extends StatefulWidget {
  final List<Season> seasons;
  final Function(int index, int start, int end) onChanged;

  const MonthSlider({
    Key? key,
    required this.seasons,
    required this.onChanged,
  }) : super(key: key);

  @override
  State<MonthSlider> createState() => _MonthSliderState();
}

class _MonthSliderState extends State<MonthSlider> {
  bool _isDragging = false;
  int? _draggingSeasonIndex;
  int? _draggingHandle;

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final monthHeight = (constraints.maxHeight - 24) / 11;

        return Stack(
          children: [
            // Background line
            Center(
              child: Container(
                width: 4,
                height: constraints.maxHeight - 24,
                margin: const EdgeInsets.symmetric(vertical: 12),
                decoration: BoxDecoration(
                  color: Colors.grey[800],
                  borderRadius: BorderRadius.circular(2),
                ),
              ),
            ),
            // Draw all seasons
            ...widget.seasons.map((season) {
              final index = widget.seasons.indexOf(season);
              return _buildSeasonRange(season, index, monthHeight);
            }),
            // Gesture detector
            GestureDetector(
              onVerticalDragStart: (details) =>
                  _handleDragStart(details, monthHeight),
              onVerticalDragUpdate: (details) =>
                  _handleDragUpdate(details, monthHeight),
              onVerticalDragEnd: _handleDragEnd,
              child: Container(color: Colors.transparent),
            ),
          ],
        );
      },
    );
  }

  Widget _buildSeasonRange(Season season, int index, double monthHeight) {
    return Stack(
      children: [
        // Active range
        Positioned(
          left: 0,
          right: 0,
          top: _getMonthPosition(season.startMonth, monthHeight),
          height: _getMonthPosition(season.endMonth, monthHeight) -
              _getMonthPosition(season.startMonth, monthHeight),
          child: Center(
            child: Container(
              width: 4,
              decoration: BoxDecoration(
                color: season.color,
                borderRadius: BorderRadius.circular(2),
              ),
            ),
          ),
        ),
        // Handles
        _buildHandle(season.startMonth, monthHeight, season.color, true),
        _buildHandle(season.endMonth, monthHeight, season.color, false),
      ],
    );
  }

  Widget _buildHandle(int month, double monthHeight, Color color, bool isTop) {
    return Positioned(
      left: 0,
      right: 0,
      top: _getMonthPosition(month, monthHeight) - 12,
      height: 24,
      child: Center(
        child: Container(
          width: 12,
          height: 12,
          decoration: BoxDecoration(
            color: color,
            shape: BoxShape.circle,
            border: Border.all(color: Colors.white, width: 2),
          ),
        ),
      ),
    );
  }

  double _getMonthPosition(int month, double monthHeight) {
    return 12 + month * monthHeight;
  }

  int _getMonthFromPosition(double position, double monthHeight) {
    return ((position - 12) / monthHeight).round().clamp(0, 11);
  }

  void _handleDragStart(DragStartDetails details, double monthHeight) {
    final RenderBox box = context.findRenderObject() as RenderBox;
    final localPosition = box.globalToLocal(details.globalPosition);

    // 找到最近的手柄
    double minDistance = double.infinity;
    int? closestSeasonIndex;
    bool? isTopHandle;

    for (int i = 0; i < widget.seasons.length; i++) {
      final season = widget.seasons[i];
      final topY = _getMonthPosition(season.startMonth, monthHeight);
      final bottomY = _getMonthPosition(season.endMonth, monthHeight);

      final distanceToTop = (localPosition.dy - topY).abs();
      final distanceToBottom = (localPosition.dy - bottomY).abs();

      if (distanceToTop < minDistance) {
        minDistance = distanceToTop;
        closestSeasonIndex = i;
        isTopHandle = true;
      }
      if (distanceToBottom < minDistance) {
        minDistance = distanceToBottom;
        closestSeasonIndex = i;
        isTopHandle = false;
      }
    }

    // 只有当点击位置足够接近手柄且找到了有效的季节索引时才开始拖动
    if (minDistance < 20 && closestSeasonIndex != null && isTopHandle != null) {
      _isDragging = true;
      _draggingSeasonIndex = closestSeasonIndex;
      _draggingHandle = isTopHandle ? 0 : 1;
    }
  }

  void _handleDragUpdate(DragUpdateDetails details, double monthHeight) {
    if (!_isDragging || _draggingSeasonIndex == null || _draggingHandle == null)
      return;

    final RenderBox box = context.findRenderObject() as RenderBox;
    final localPosition = box.globalToLocal(details.globalPosition);
    int month = _getMonthFromPosition(localPosition.dy, monthHeight);

    final season = widget.seasons[_draggingSeasonIndex!];
    if (_draggingHandle == 0) {
      // 拖动上端，确保不超过下端
      if (month < season.endMonth) {
        widget.onChanged(_draggingSeasonIndex!, month, season.endMonth);
      }
    } else {
      // 拖动下端，确保不低于上端
      if (month > season.startMonth) {
        widget.onChanged(_draggingSeasonIndex!, season.startMonth, month);
      }
    }
  }

  void _handleDragEnd(DragEndDetails details) {
    _isDragging = false;
    _draggingHandle = null;
  }
}












class Season {
  int startMonth;
  int endMonth;
  Color color;

  Season({
    required this.startMonth,
    required this.endMonth,
    required this.color,
  });
}

class SeasonsPage extends StatefulWidget {
  const SeasonsPage({Key? key}) : super(key: key);

  @override
  State<SeasonsPage> createState() => _SeasonsPageState();
}

class _SeasonsPageState extends State<SeasonsPage> {
  final List<String> months = [
    'Jan',
    'Feb',
    'Mar',
    'Apr',
    'May',
    'Jun',
    'Jul',
    'Aug',
    'Sep',
    'Oct',
    'Nov',
    'Dec'
  ];

  // 预定义的季节颜色
  final List<Color> seasonColors = [
    Colors.blue,
    Colors.green,
    Colors.orange,
    Colors.purple,
    Colors.red,
    Colors.teal,
  ];

  late List<Season> _seasons;

  @override
  void initState() {
    super.initState();
    // 初始化一个完整的季节（1-12月）
    _seasons = [
      Season(
        startMonth: 0,
        endMonth: 11,
        color: seasonColors[0],
      ),
    ];
  }

  void _addSeason() {
    if (_seasons.length >= seasonColors.length) return;

    // 找到最后一个季节
    final lastSeason = _seasons.last;
    final monthsInLastSeason = lastSeason.endMonth - lastSeason.startMonth + 1;

    if (monthsInLastSeason >= 2) {
      // 将最后一个季节平均分成两部分
      final splitPoint = lastSeason.startMonth + (monthsInLastSeason ~/ 2);

      setState(() {
        // 更新最后一个季节的结束月份
        lastSeason.endMonth = splitPoint - 1;

        // 添加新季节
        _seasons.add(Season(
          startMonth: splitPoint,
          endMonth: lastSeason.endMonth,
          color: seasonColors[_seasons.length],
        ));
      });
    }
  }

  void _removeSeason() {
    if (_seasons.length <= 1) return; // 保持至少一个季节

    setState(() {
      final removedSeason = _seasons.removeLast();
      final lastSeason = _seasons.last;
      // 将被删除季节的月份合并到前一个季节
      lastSeason.endMonth = removedSeason.endMonth;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.black,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () => Navigator.pop(context),
        ),
        title: const Text(
          'Seasons',
          style: TextStyle(color: Colors.white),
        ),
        actions: [
          TextButton(
            onPressed: () {
              // Handle next action
            },
            child: const Text(
              'Next',
              style: TextStyle(color: Colors.blue),
            ),
          ),
        ],
      ),
      body: Column(
        children: [
          Expanded(
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 40.0),
              child: Row(
                children: [
                  // Season labels
                  Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: _seasons.map((season) {
                      final index = _seasons.indexOf(season);
                      return Padding(
                        padding: const EdgeInsets.symmetric(vertical: 8.0),
                        child: Text(
                          'Season ${index + 1}',
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 16,
                          ),
                        ),
                      );
                    }).toList(),
                  ),
                  const SizedBox(width: 40),
                  // Month slider and labels
                  Expanded(
                    child: Stack(
                      children: [
                        // Month labels
                        Positioned.fill(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: months
                                .map((month) => Text(
                              month,
                              style: TextStyle(
                                color: Colors.white.withOpacity(0.8),
                                fontSize: 14,
                              ),
                            ))
                                .toList(),
                          ),
                        ),
                        // Combined month slider
                        MonthSlider(
                          seasons: _seasons,
                          onChanged: (index, start, end) {
                            setState(() {
                              bool canUpdate = true;
                              // 检查是否与其他季节重叠
                              for (int i = 0; i < _seasons.length; i++) {
                                if (i != index &&
                                    _isOverlapping(
                                        start,
                                        end,
                                        _seasons[i].startMonth,
                                        _seasons[i].endMonth)) {
                                  canUpdate = false;
                                  break;
                                }
                              }
                              if (canUpdate) {
                                _seasons[index].startMonth = start;
                                _seasons[index].endMonth = end;
                              }
                            });
                          },
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
          // 底部按钮保持不变
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.grey[900],
                      foregroundColor: Colors.white,
                      padding: const EdgeInsets.symmetric(vertical: 16),
                    ),
                    onPressed: _removeSeason,
                    child: const Text('Remove Season'),
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.white,
                      foregroundColor: Colors.black,
                      padding: const EdgeInsets.symmetric(vertical: 16),
                    ),
                    onPressed: _addSeason,
                    child: const Text('Add Season'),
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 16),
        ],
      ),
    );
  }

  bool _isOverlapping(int start1, int end1, int start2, int end2) {
    return start1 <= end2 && end1 >= start2;
  }
}


